package br.edu.ufabc.gtrnp.helppo.business;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import br.edu.ufabc.gtrnp.helppo.persistence.entity.InventoryFolders;
import br.edu.ufabc.gtrnp.helppo.persistence.entity.InventoryItems;
import br.edu.ufabc.gtrnp.helppo.persistence.entity.Usuario;
import br.edu.ufabc.gtrnp.helppo.util.HelppoConstants;

import com.eaio.uuid.UUID;

public class InventarioBusiness {

	String[] pastas = { "Animations", "Body Parts", "Calling Cards",
			"Clothing", "Gestures", "Landmarks", "Lost And Found", "Notecards",
			"Objects", "Photo Album", "Scripts", "Sounds", "Textures", "Trash",
			HelppoConstants.FOLDER_NAME };
	int[] tipos = { 20, 13, 2, 5, 21, 3, 16, 7, 6, 15, 10, 1, 0, 14, 10 };

	private static InventarioBusiness business = new InventarioBusiness();

	private InventarioBusiness() {
	}

	public static InventarioBusiness getInstance() {
		return business;
	}

	public void criarPastasInventario(Usuario usuario) {

		GenericDAO dao = new GenericDAO();
		Session session = dao.getCurrentSession();
		// pastaraiz
		InventoryFolders raiz = new InventoryFolders();
		raiz.setFolderID((new UUID()).toString());
		raiz.setAgentID(usuario.getUUID());
		raiz.setFolderName("My Inventory");
		raiz.setParentFolderID("00000000-0000-0000-0000-000000000000");
		raiz.setType(8);
		raiz.setVersion(1);
		session.persist(raiz);

		// laco pra criar as pastas filha
		for (int i = 0; i < pastas.length; i++) {
			InventoryFolders pasta = new InventoryFolders();
			pasta.setFolderID((new UUID()).toString());
			pasta.setAgentID(usuario.getUUID());
			pasta.setFolderName(pastas[i]);
			pasta.setParentFolderID(raiz.getFolderID());
			pasta.setType(tipos[i]);
			pasta.setVersion(1);
			session.persist(pasta);
			pasta = null;
		}

	}
	
	@SuppressWarnings("unchecked")
	public List<InventoryItems> recuperaItensInventario(Usuario usuario){
		GenericDAO dao = new GenericDAO();
		Session session = dao.getCurrentSession();
		
		String hql = "FROM InventoryFolders WHERE agentID =:a and folderName=:b";
		
		Query query = session.createQuery(hql);
		query.setString("a", usuario.getUUID());
		query.setString("b", HelppoConstants.FOLDER_NAME);
		
		InventoryFolders pasta = (InventoryFolders)query.uniqueResult();
		
		if(pasta == null)return null;
		
		hql = "FROM InventoryItems WHERE parentFolderID =:a";
		query = session.createQuery(hql);
		query.setString("a", pasta.getFolderID());
		return (List<InventoryItems>) query.list();
	}
	
}
